﻿using System;
using System.Text;
using System.Collections;
using RAP.Framework.Libary.DomTemplateBuilder.Element;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.ExpressionCompiler;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler
{
	/// <summary>
	/// 表达式处理器，可执行C#代码
	/// </summary>
	public class RunHandler : HandlerBase
	{
		public override void DoRender( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var sb = new StringBuilder();
			base.DoRender( sb, rootParamObject, parentParamObject, context );
			var content = sb.ToString();
			if ( content.IsNotNullOrEmpty() )
			{
				try
				{
					var handler = CSCompiler.CompileDelegate<Action<StringBuilder, object, object, IDictionary>>( content, "response,param,parent,context" );
					handler( writer, rootParamObject, parentParamObject, context );
				}
				catch ( Exception ex )
				{
					var ele = this.Element as Run;
					if ( ele.ErrorMessage.IsNotNullOrEmpty() )
					{
						throw new Exception( ele.ErrorMessage );
					}
					else
					{
						throw ex;
					}
				}
			}
			else if ( !( this.Element as Expression ).IgnoreEmpty )
			{
				throw new NullReferenceException( "表达式不能为空！如果想忽略该错误，请将Expression节点的IgnoreEmpty设置为true。" );
			}
		}
	}
};